#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
路径配置模块
集中管理项目中的所有路径配置，提高可移植性和可维护性
"""

import os
import platform
from pathlib import Path


class PathConfig:
    """路径配置类，根据操作系统和发行版动态生成路径"""
    
    def __init__(self):
        self.os_type = platform.system().lower()
        self.is_windows = self.os_type == 'windows'
        self.is_linux = self.os_type == 'linux'
        self.is_macos = self.os_type == 'darwin'
        
        # 获取当前用户主目录
        self.home_dir = str(Path.home())
        
        # 初始化路径配置
        self._init_system_paths()
        self._init_log_paths()
        self._init_config_paths()
        self._init_temp_paths()
        self._init_service_paths()
    
    def _init_system_paths(self):
        """初始化系统路径"""
        if self.is_windows:
            self.system_paths = {
                'bin': ['C:\\Windows\\System32', 'C:\\Windows'],
                'config': ['C:\\ProgramData', 'C:\\Windows\\System32\\config'],
                'temp': ['C:\\Temp', 'C:\\Windows\\Temp'],
                'user_profile': os.environ.get('USERPROFILE', 'C:\\Users\\Default'),
                'program_files': os.environ.get('PROGRAMFILES', 'C:\\Program Files'),
            }
        else:
            self.system_paths = {
                'bin': ['/usr/bin', '/usr/local/bin', '/bin'],
                'sbin': ['/usr/sbin', '/sbin'],
                'lib': ['/usr/lib', '/lib', '/usr/local/lib'],
                'etc': '/etc',
                'var': '/var',
                'opt': '/opt',
                'proc': '/proc',
                'sys': '/sys',
                'dev': '/dev',
                'tmp': '/tmp',
                'var_tmp': '/var/tmp',
                'dev_shm': '/dev/shm',
            }
    
    def _init_log_paths(self):
        """初始化日志路径"""
        if self.is_windows:
            self.log_paths = {
                'system': ['C:\\Windows\\Logs', 'C:\\ProgramData\\logs'],
                'application': ['C:\\ProgramData\\privilege_ma\\logs'],
                'temp_logs': ['C:\\Temp\\logs'],
            }
        else:
            self.log_paths = {
                'system': ['/var/log'],
                'auth': ['/var/log/auth.log', '/var/log/secure'],
                'syslog': ['/var/log/syslog', '/var/log/messages'],
                'audit': ['/var/log/audit/audit.log'],
                'application': ['/var/log/privilege_ma'],
                'temp_logs': ['/tmp/logs', '/var/tmp/logs'],
            }
    
    def _init_config_paths(self):
        """初始化配置文件路径"""
        if self.is_windows:
            self.config_paths = {
                'system': ['C:\\ProgramData', 'C:\\Windows\\System32\\config'],
                'user': [os.path.join(self.home_dir, 'AppData', 'Roaming')],
                'application': ['C:\\ProgramData\\privilege_ma'],
            }
        else:
            self.config_paths = {
                'system': ['/etc'],
                'user': [os.path.join(self.home_dir, '.config')],
                'ssh': ['/etc/ssh', os.path.join(self.home_dir, '.ssh')],
                'cron': ['/etc/cron.d', '/etc/cron.daily', '/etc/cron.hourly', 
                        '/etc/cron.monthly', '/etc/cron.weekly'],
                'systemd': ['/etc/systemd/system', '/usr/lib/systemd/system', 
                           '/lib/systemd/system'],
                'application': ['/etc/privilege_ma', os.path.join(self.home_dir, '.privilege_ma')],
            }
    
    def _init_temp_paths(self):
        """初始化临时文件路径"""
        if self.is_windows:
            self.temp_paths = {
                'system': ['C:\\Temp', 'C:\\Windows\\Temp'],
                'user': [os.environ.get('TEMP', 'C:\\Temp')],
                'application': ['C:\\Temp\\privilege_ma'],
            }
        else:
            self.temp_paths = {
                'system': ['/tmp', '/var/tmp'],
                'memory': ['/dev/shm'],
                'user': [os.path.join(self.home_dir, '.cache')],
                'application': ['/tmp/privilege_ma', '/var/tmp/privilege_ma'],
            }
    
    def _init_service_paths(self):
        """初始化服务相关路径"""
        if self.is_windows:
            self.service_paths = {
                'services': ['C:\\Windows\\System32\\services.exe'],
                'scheduled_tasks': ['C:\\Windows\\System32\\Tasks'],
            }
        else:
            self.service_paths = {
                'systemd': ['/etc/systemd/system', '/usr/lib/systemd/system'],
                'init_d': ['/etc/init.d'],
                'cron': ['/etc/crontab', '/var/spool/cron'],
                'ssh': ['/etc/ssh/sshd_config'],
            }
    
    def get_os_release_files(self):
        """获取操作系统发行版信息文件路径"""
        if self.is_linux:
            return [
                '/etc/os-release',
                '/etc/redhat-release',
                '/etc/debian_version',
                '/etc/fedora-release',
                '/etc/centos-release',
                '/etc/SuSE-release',
                '/etc/alpine-release',
                '/etc/lsb-release',
            ]
        return []
    
    def get_package_manager_paths(self, distro_type=None):
        """根据发行版类型获取包管理器路径"""
        if not self.is_linux:
            return {}
        
        paths = {
            'debian_based': {
                'config': ['/etc/apt', '/etc/dpkg'],
                'cache': ['/var/cache/apt', '/var/lib/dpkg'],
                'logs': ['/var/log/apt', '/var/log/dpkg.log'],
            },
            'rhel_based': {
                'config': ['/etc/yum.conf', '/etc/yum.repos.d', '/etc/dnf'],
                'cache': ['/var/cache/yum', '/var/cache/dnf'],
                'logs': ['/var/log/yum.log', '/var/log/dnf.log'],
            },
            'suse_based': {
                'config': ['/etc/zypp'],
                'cache': ['/var/cache/zypp'],
                'logs': ['/var/log/zypper.log'],
            },
            'alpine_based': {
                'config': ['/etc/apk'],
                'cache': ['/var/cache/apk'],
                'logs': ['/var/log/messages'],
            },
        }
        
        if distro_type:
            return paths.get(distro_type, {})
        return paths
    
    def get_user_history_paths(self, username=None):
        """获取用户历史记录文件路径"""
        if self.is_windows:
            return []
        
        base_paths = []
        if username:
            base_paths = [f'/home/{username}', f'/var/home/{username}']
        else:
            base_paths = [self.home_dir]
        
        history_files = []
        for base_path in base_paths:
            history_files.extend([
                os.path.join(base_path, '.bash_history'),
                os.path.join(base_path, '.zsh_history'),
                os.path.join(base_path, '.history'),
                os.path.join(base_path, '.local/share/fish/fish_history'),
            ])
        
        # 添加系统级历史文件
        history_files.extend([
            '/root/.bash_history',
            '/root/.zsh_history',
            '/boot/efi/.bash_history',
        ])
        
        return history_files
    
    def get_secure_temp_path(self):
        """获取安全的临时文件路径"""
        if self.is_windows:
            return os.path.join(os.environ.get('TEMP', 'C:\\Temp'), 'privilege_ma')
        else:
            # 优先使用内存文件系统
            if os.path.exists('/dev/shm'):
                return '/dev/shm/privilege_ma'
            return '/tmp/privilege_ma'
    
    def ensure_path_exists(self, path):
        """确保路径存在，如果不存在则创建"""
        try:
            os.makedirs(path, exist_ok=True)
            return True
        except (OSError, PermissionError):
            return False
    
    def get_writable_paths(self, path_list):
        """从路径列表中筛选出可写的路径"""
        writable = []
        for path in path_list:
            try:
                if os.path.exists(path) and os.access(path, os.W_OK):
                    writable.append(path)
                elif not os.path.exists(path):
                    # 尝试创建路径
                    if self.ensure_path_exists(path):
                        writable.append(path)
            except (OSError, PermissionError):
                continue
        return writable
    
    def get_readable_paths(self, path_list):
        """从路径列表中筛选出可读的路径"""
        readable = []
        for path in path_list:
            try:
                if os.path.exists(path) and os.access(path, os.R_OK):
                    readable.append(path)
            except (OSError, PermissionError):
                continue
        return readable


# 全局路径配置实例
path_config = PathConfig()


def get_system_path(path_type, fallback=None):
    """获取系统路径的便捷函数"""
    paths = getattr(path_config, f'{path_type}_paths', {})
    if isinstance(paths, dict):
        return paths
    elif isinstance(paths, list) and paths:
        return paths[0]
    return fallback


def get_first_existing_path(path_list):
    """从路径列表中返回第一个存在的路径"""
    for path in path_list:
        if os.path.exists(path):
            return path
    return None


def get_safe_path(path_list, check_writable=False):
    """获取安全可用的路径"""
    if check_writable:
        return path_config.get_writable_paths(path_list)
    else:
        return path_config.get_readable_paths(path_list)